package com.woniu.Service.impl;


import com.woniu.Service.UserRoleService;
import com.woniu.entity.UserRole;
import com.woniu.mapper.UserRoleMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @Author: Gwj
 * @Date: 2024/7/4 17:04
 */
@Service
@Transactional
public class UserRoleServiceImpl implements UserRoleService {
    @Resource
    private UserRoleMapper userRoleMapper;

    /**
     * 获取用户的角色
     *
     * @param accountId
     * @return
     * @throws Exception
     */
    @Override
    public Set<Integer> getRoleByAccountId(Integer accountId) throws Exception {
        Example example = new Example(UserRole.class);
        Example.Criteria c = example.createCriteria();
        c.andEqualTo("accountId", accountId);
        List<UserRole> userRoles = userRoleMapper.selectByExample(example);
        HashSet<Integer> set = new HashSet<>();
        for (UserRole userRole : userRoles) {
            set.add(userRole.getRoleId());
        }
        return set;
    }

    /**
     * 增加用户的权限
     *
     * @param accountId
     * @param list
     * @return
     * @throws Exception
     */
    @Override
    public int addRoleByAccountId(Integer accountId, List<UserRole> list) throws Exception {
        //先删除用户原有的权限
        Example example = new Example(UserRole.class);
        Example.Criteria c = example.createCriteria();
        c.andEqualTo("accountId", accountId);
        userRoleMapper.deleteByExample(example);

        //再添加用户权限
        int i = userRoleMapper.insertUserRole(list);
        return i;
    }
}
